package com.zz.xapp.config

import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.zz.framework.core.BaseApp
import com.zz.framework.core.http.BaseOkHttpClient
import com.zz.framework.core.http.BaseRetrofitConfig
import com.zz.framework.core.utils.NetWorkUtils
import com.zz.xapp.interceptor.CommonParameterInterceptor
import com.zz.xapp.interceptor.CookieInterceptor
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.io.File

/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created by zanezhao on 2020/3/1 3:42 PM.
 * @author: zanezhao 1820022519@qq.com
 * @version: V1.0
 */
class AppRetrofitConfig : BaseRetrofitConfig() {

    override fun initOkHttpClient(vararg interceptors: Interceptor): OkHttpClient {
        return BaseOkHttpClient.create(*initInterceptors() ,blockBuilder = {
            handleBuilder(it)
        })
    }

    override fun initInterceptors(): Array<Interceptor> {
        var mInterceptors = mutableListOf<Interceptor>()
        mInterceptors.add(CommonParameterInterceptor.builder())
        mInterceptors.add(CookieInterceptor.builder())
        return mInterceptors.toTypedArray()
    }

    private val cookieJar by lazy {
        PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(BaseApp.context))
    }

    override fun handleBuilder(builder: OkHttpClient.Builder) {
        val httpCacheDirectory = File(BaseApp.context.cacheDir, "responses")
        val cacheSize = 10 * 1024 * 1024L // 10 MiB
        val cache = Cache(httpCacheDirectory, cacheSize)
        builder.cache(cache)
            .cookieJar(cookieJar)
            .addInterceptor { chain ->
                var request = chain.request()
                if (!NetWorkUtils.isNetworkAvailable(BaseApp.context)) {
                    request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build()
                }
                val response = chain.proceed(request)
                if (!NetWorkUtils.isNetworkAvailable(BaseApp.context)) {
                    val maxAge = 60 * 60
                    response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=$maxAge")
                        .build()
                } else {
                    val maxStale = 60 * 60 * 24 * 28 // tolerate 4-weeks stale
                    response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
                        .build()
                }
                response
            }
    }

}